package org.reborn.engine.render.texture

import java.nio.Buffer
import javax.media.opengl.{GL,GL2,GL2GL3,GL2ES1}

trait TexCubeMap extends Tex2D{
  self: TextureMetadata =>
  override val glTarget:Int = GL.GL_TEXTURE_CUBE_MAP
  override val texDimensions:Int = 2
}

class TextureCubeMapMetadata extends TexCubeMap with BaseTextureMetadata 

/**
 * Create a new OpenGL texture.
 * @param metadata The TextureCubeMapMetadata associated with this texture
 * 
 * @define imagesDescription An array of Buffers that specify the image(s) used to create the texture.
 * The texture requires at least six Buffers, one for each side of the cube, but additional multiples of
 * 6 Buffers may be specified to create mipmaps. 
 * The first 6 Buffers correspond to the zeroth mipmap, and each set of 6 Buffers afterwards correspond to the next
 * mipmap level. The Buffer order for each set of 6 images must be specified in the following order: 
 * Negative X, Positive X, Negative Y, Positive Y, Negative Z, Positive Z 
 */
class TextureCubeMap(val metadata:TextureCubeMapMetadata) extends Texture {

  protected def setImageData(gl: GL, images: Seq[Buffer], glFormat:Int, glType: Int): Unit = {
	var img = 0
	while(img < images.size){
	  val level = img / 6
	  
	  val imgData = images(img)
	  imgData.rewind
	  
	  gl.glTexImage2D(getTarget(img), level, metadata.glInternalFormat, metadata.width, metadata.height, 0, glFormat, glType, imgData)
	  img += 1
	}
  }

  protected def getTarget(index:Int):Int = {
	(index % 6) match{
		case 0 => GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X
		case 1 => GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X
		case 2 => GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y
		case 3 => GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
		case 4 => GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Z
		case 5 => GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
	}
  }
}
